package com.approval.controller;

import com.approval.dto.*;
import com.approval.entity.User;
import com.approval.security.JwtTokenProvider;
import com.approval.service.AuthService;
import com.approval.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;
    
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest request) {
        try {
            // 使用Spring Security进行认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );
            
            // 生成JWT token
            String token = jwtTokenProvider.generateToken(authentication);
            
            // 获取用户信息
            User user = userService.getCurrentUser();
            
            // 获取用户权限
            List<String> permissions = authService.getUserPermissionCodes(user.getId());
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", token);
            result.put("permissions", permissions);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("登录失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = userService.register(request);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/current")
    public Result<User> getCurrentUser() {
        try {
            User user = userService.getCurrentUser();
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("获取当前用户失败: " + e.getMessage());
        }
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/user-roles")
    @PreAuthorize("hasPermission('auth', 'user-role')")
    public ResponseEntity<Result<Void>> assignRolesToUser(@Valid @RequestBody UserRoleAssignRequest request) {
        try {
            authService.assignRolesToUser(request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 为角色分配权限
     */
    @PostMapping("/role-permissions")
    @PreAuthorize("hasPermission('auth', 'role-permission')")
    public ResponseEntity<Result<Void>> assignPermissionsToRole(@Valid @RequestBody RolePermissionAssignRequest request) {
        try {
            authService.assignPermissionsToRole(request);
            return ResponseEntity.ok(Result.success());
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 获取用户权限预览
     */
    @GetMapping("/user/{userId}/preview")
    @PreAuthorize("hasPermission('auth', 'user-role')")
    public ResponseEntity<Result<UserPermissionPreviewResponse>> getUserPermissionPreview(@PathVariable Long userId) {
        try {
            UserPermissionPreviewResponse preview = authService.getUserPermissionPreview(userId);
            return ResponseEntity.ok(Result.success(preview));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 获取角色权限预览
     */
    @GetMapping("/role/{roleId}/preview")
    @PreAuthorize("hasPermission('auth', 'role-permission')")
    public ResponseEntity<Result<RolePermissionPreviewResponse>> getRolePermissionPreview(@PathVariable Long roleId) {
        try {
            RolePermissionPreviewResponse preview = authService.getRolePermissionPreview(roleId);
            return ResponseEntity.ok(Result.success(preview));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 检查用户是否有指定权限
     */
    @GetMapping("/check-permission")
    public ResponseEntity<Result<Boolean>> hasPermission(@RequestParam Long userId,
                                                         @RequestParam String permissionCode) {
        try {
            boolean hasPermission = authService.hasPermission(userId, permissionCode);
            return ResponseEntity.ok(Result.success(hasPermission));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 检查用户是否有指定资源和操作的权限
     */
    @GetMapping("/check-resource")
    public ResponseEntity<Result<Boolean>> hasResourcePermission(@RequestParam Long userId,
                                                                 @RequestParam String resource,
                                                                 @RequestParam String operation) {
        try {
            boolean hasPermission = authService.hasPermission(userId, resource, operation);
            return ResponseEntity.ok(Result.success(hasPermission));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 获取用户的所有权限编码
     */
    @GetMapping("/user/{userId}/permission-codes")
    public ResponseEntity<Result<List<String>>> getUserPermissionCodes(@PathVariable Long userId) {
        try {
            List<String> permissionCodes = authService.getUserPermissionCodes(userId);
            return ResponseEntity.ok(Result.success(permissionCodes));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 获取用户的菜单权限
     */
    @GetMapping("/user/{userId}/menu-permissions")
    public ResponseEntity<Result<List<PermissionResponse>>> getUserMenuPermissions(@PathVariable Long userId) {
        try {
            List<PermissionResponse> permissions = authService.getUserMenuPermissions(userId);
            return ResponseEntity.ok(Result.success(permissions));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }

    /**
     * 获取用户的操作权限
     */
    @GetMapping("/user/{userId}/operation-permissions")
    public ResponseEntity<Result<List<PermissionResponse>>> getUserOperationPermissions(@PathVariable Long userId) {
        try {
            List<PermissionResponse> permissions = authService.getUserOperationPermissions(userId);
            return ResponseEntity.ok(Result.success(permissions));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error(e.getMessage()));
        }
    }
}

